package com.tech15.core.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javacommon.util.PropertiesUtil;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.tech15.core.model.Attach;
import com.tech15.core.service.AttachManager;

public class DownloadAction  extends ActionSupport {
	
	private final static String DOWNLOADFILEPATH = "/uploaddata/";

	private String inputPath;
	private String contentType;
	private String filename;
	private InputStream inputName;
	
	//private InputStream inputStream;
	
	
	private AttachManager attachManager;

	public void setAttachManager(AttachManager attachManager) {
		this.attachManager = attachManager;
	}

	public String getContentType() {
		return contentType;
	}

	public String getFilename() {
		String downloadChineseFileName = filename;
		try {
			downloadChineseFileName = new String(filename.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downloadChineseFileName;
	}

//	 从下载文件原始存放路径读取得到文件输出流
	public InputStream getDownloadFile() {
		//return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
		try {
			return new FileInputStream(new File(inputPath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	
	public String execute() throws Exception {
		Attach attach = attachManager.getById(fileAsName);
		//inputPath = DOWNLOADFILEPATH + attach.getPath();
		String allowUploadPath = PropertiesUtil.getResourceBundle().getString("allowUploadPath");
		if(allowUploadPath.equals("true")){
			String uploadPath = PropertiesUtil.getResourceBundle().getString("uploadPath");
			inputPath = uploadPath + attach.getPath();
		}else{
			inputPath = DOWNLOADFILEPATH + attach.getPath();
		}
		filename = attach.getName(); // 保存文件时的名称
		contentType = attach.getContType();// 保存文件的类型
		return SUCCESS;
	}
	
	private String fileAsName;

	public String getFileAsName() {
		return fileAsName;
	}

	public void setFileAsName(String fileAsName) {
		this.fileAsName = fileAsName;
	}

	public String getInputPath() {
		return inputPath;
	}

}